<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 佛山维亚轩科技，并保留所有权利。
 * 网站地址: http://www.vyxjj.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 */

namespace Admin\Controller;
use Admin\Logic\GoodsLogic;
use ZipArchive;
class UpdateController extends BaseController{	
	
	public function update()
    {
		$updatehost = 'http://v1.weixinfenxiaoshop.com/update.php';
		$version = 'Public/version.json';
		$json_string = file_get_contents($version);
		$data = json_decode($json_string, true);
		$ver = $data['version'];
		$this->assign('ver_now', $ver);
		$key = file_get_contents("Public/update.txt");
		$hosturl = $_SERVER['HTTP_HOST'];
		$gettimeurl = $updatehost . '?a=client_check_time&v=' . $ver . '&u=' . $hosturl. '&key=' . $key;
		

		$domain_time = file_get_contents($gettimeurl);
		if($domain_time==false){
			$this->error("网站未授权，或未开启服务器CURL组件",U('Admin/Index/welcome'));
		}
		if (!file_exists("Public/update.txt")) {
			$this->display('update_key');
        }else if($domain_time){
			$lastver = file_get_contents(($updatehost . '?a=check&v=') . $ver);
			//if(0){
			if($lastver !== $ver){
				$update_url = U('Admin/Update/updatenow');
				$updateinfo = '<span>
			   <a href="javascript:if(confirm(\'升级前,请确认已经做好数据库和程序备份!\'))location=\''.$update_url.'\'"><button class="btn btn-primary" type="button" >点击这里在线升级</button></a>
			   </span>';
				$chanageinfo = file_get_contents(($updatehost . '?a=chanage&v=') . $lastver);
				$this->assign('chanageinfo',$chanageinfo);
				$this->assign('updateinfo',$updateinfo);
			}else{
				$this->assign('chanageinfo',"最新版本为：维亚轩多店铺系统v".$lastver);
				$this->assign('updateinfo',"已经是最新系统 不需要升级<br/>");
			}
			$this->display();
		}else{
			$this->error("该系统未授权，不能使用在线更新",U('Admin/Index/welcome'));
		}
    }
	public function add_key()
    {   
		$key=$_POST['key'];
		$file = fopen("Public/update.txt","w");
		fwrite($file,$key);
		$this->success("授权秘钥添加成功",U('Admin/Update/upload'));
    }
	//新增 微信小程序跳转的appid
	public function add_jump()
	{
		$jump_appid_list = file_get_contents("Public/jump_appid_list.txt");
		$jump_appid_list=unserialize($jump_appid_list);
		$this->assign('jump_appid_list',$jump_appid_list);
		$this->display('add_jump');
		
	}
	//更新小程序 
	public function update_jump()
    {   
		$jump_appid_list=$_POST['jump_appid_list'];
		$res=file_put_contents("Public/jump_appid_list.txt", serialize($jump_appid_list));
		if($res){
			$this->success("更新跳转小程序资料成功",U('Admin/Update/upload'));
		}else{
			
			$this->error("设置失败，请检查Public/jump_appid_list.txt是否有可写权限",U('Admin/Update/add_jump'));
		}
    }
	public function updatenow()
    {
		$updatehost = 'http://v1.weixinfenxiaoshop.com/update.php';
		$version = 'Public/version.json';
		$json_string = file_get_contents($version);
		$data = json_decode($json_string, true);
		$ver = $data['version'];
		$key = file_get_contents("Public/update.txt");
		$hosturl = $_SERVER['HTTP_HOST'];
		$gettimeurl = $updatehost . '?a=client_check_time&v=' . $ver . '&u=' . $hosturl. '&key=' . $key;
		$domain_time = file_get_contents($gettimeurl);

        $updatehosturl = $updatehost . '?a=update&v=' . $ver . '&u=' . $hosturl. '&key=' . $key;
        $updatenowinfo = file_get_contents($updatehosturl);
		$res = json_decode($updatenowinfo, true);
		
		if($res['code']==1){
			
			$this->error($res['msg'],U('Admin/Update/update'));
			
		}

        if (strstr($res['data']['src_file'], 'zip')){
            $pathurl = $updatehost . '?a=down&f=' . $res['data']['src_file'];
            $updatedir = 'Public/update/';

			$get_res_src=$this->get_file($pathurl, $res['data']['src_file'], $updatedir);
			if(!$get_res_src){
				
				$this->error("缺失更新文件，请等待",U('Admin/Update/update'));
			}
			if($res['data']['db_file']){
				$pathurl = $updatehost . '?a=down&f=' . $res['data']['db_file'];
				$get_res_db=$this->get_file($pathurl, $res['data']['db_file'], $updatedir);
				if(!$get_res_db){
					$this->error("数据库更新文件缺失",U('Admin/Update/update'));
				}else{
					$sql = $updatedir.$res['data']['db_file'];
					$sql = file_get_contents($sql);
					M()->execute($sql);
				}
			}else{
				
				$this->error("更新补丁设置错误",U('Admin/Update/update'));
			}
			$zip = new ZipArchive;
			$result = $zip->open($updatedir.$res['data']['src_file']);
			if($result=== TRUE){
				$result =$zip->extractTo('Public/../');
				if($result=== TRUE){
					$zip->close();
					unlink($updatedir.$res['data']['src_file']);
					unlink($updatedir.$res['data']['db_file']);
					$version_info['version']=$res['data']['target_version'];
					$json_string = json_encode($version_info);
					$json_string = file_put_contents($version,$json_string);
					if($json_string){
						$result_update = $updatehost . '?a=callback_update&v=' . $ver . '&u=' . $hosturl. '&key=' . $key;
						$result_update = file_get_contents($result_update);
					}
					$this->success("更新成功",U('Admin/Update/update'));
				}else{
					$this->error("站点根目录不可写",U('Admin/Update/update'));
				}				
			}else{

				$this->error("补丁文件下载失败",U('Admin/Update/update'));
			}

        }else{
			$this->error("在线更新出现故障，请联系官方客服",U('Admin/Update/update'));
		}
    }
	public function get_file($url,$name,$folder = './'){
		set_time_limit((24 * 60) * 60);

		$destination_folder = $folder . '/';
		
		$this->mkdirs($destination_folder);
		
		$newfname = $destination_folder.$name;
		$file = fopen($url, 'rb');
		if ($file) {
			$newf = fopen($newfname, 'wb');
			if ($newf) {
				while (!feof($file)) {
					fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
				}
			}
		}else{
			
			return false;
		}
		if ($file) {
			fclose($file);
		}
		if ($newf) {
			fclose($newf);
		}
		return true;
	}
	public  function mkdirs($dir, $mode = 0777)
	{
		if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
		if (!mkdirs(dirname($dir), $mode)) return FALSE;
		return @mkdir($dir, $mode);
	} 
	public function upload()
    {
		$this->display();
    }
	public function upload_scan()
    {
		$http_url = $_SERVER['HTTP_HOST'];
		$url = "http://duoyonghuopen.weixinfenxiaoshop.com/login.php";
		$xcx_info = M('plugin')->where(array('code'=>'weixin','type'=>'payment'))->find();   
		$xcx_info = unserialize($xcx_info['config_value']);
		$appid = $xcx_info['appid'];
		//维亚轩 获取 小程序跳转的appid列表
		$jump_appid_list = file_get_contents("Public/jump_appid_list.txt");
		$post_data = array ("http_url"=>"$http_url","appid"=>"$appid","jump_appid_list"=>"$jump_appid_list");
		$ch  = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$data = curl_exec($ch);
		curl_close($ch);
		$data = json_decode($data);
		$this->ajaxReturn($data); 
    }
	public function upload_preview()
    {
		$http_url = $_SERVER['HTTP_HOST'];
		$url = "http://duoyonghuopen.weixinfenxiaoshop.com/preview.php";
		$xcx_info = M('plugin')->where(array('code'=>'weixin','type'=>'payment'))->find();   
		$xcx_info = unserialize($xcx_info['config_value']);
		$appid = $xcx_info['appid'];
		$post_data = array ("http_url"=>"$http_url","appid"=>"$appid");
		$ch  = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$data = curl_exec($ch);
		curl_close($ch);
		$data = json_decode($data);
		$this->ajaxReturn($data);
    }
	public function upload_last()
    {
		$http_url = $_SERVER['HTTP_HOST'];
		$url = "http://duoyonghuopen.weixinfenxiaoshop.com/upload.php";
		$post_data = array ("http_url"=>"$http_url");
		$ch  = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$data = curl_exec($ch);
		curl_close($ch);
		$data = json_decode($data);
		$this->ajaxReturn($data);
    }
}